package com.jl.cloud.commom.utils;

import com.jl.cloud.commom.config.RedisConfig;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.*;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;


@Configuration
@ConditionalOnBean(RedisConfig.class)
@Slf4j
public class RedisUtils {


	/**
	 *全局缓存限流
	 */
	private static HashMap<String,RRateLimiter> rRateLimiterHashMap = new HashMap<>();


	/**
	 * 获取Redis分布式锁
	 * @param lockKey
	 * @return
	 */
	public static RLock getLock(String lockKey) {
		return SpringContextHolder.getBean(RedissonClient.class).getLock(lockKey);
	}





	/**
	 * 获取Redis分布式令牌桶,后期可以改成动态配置
	 * @param limiterKey
	 * @return
	 */
	public static RRateLimiter getRateLimiter(String limiterKey) {
		RRateLimiter rRateLimiter = rRateLimiterHashMap.get(limiterKey);
		if(rRateLimiter != null){
			return rRateLimiter;
		}
		synchronized (RedisUtils.class){
			RRateLimiter rateLimiterTwo = rRateLimiterHashMap.get(limiterKey);
			if(rateLimiterTwo != null){
				return rateLimiterTwo;
			}
			RRateLimiter rateLimiter =  SpringContextHolder.getBean(RedissonClient.class).getRateLimiter(limiterKey);
			rateLimiter.trySetRate(RateType.OVERALL,1,2, RateIntervalUnit.SECONDS);
			rRateLimiterHashMap.put(limiterKey,rateLimiter);
			return rateLimiter;
		}
	}










}
